package com.signin.controller;

import com.signin.service.SignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@RestController
@RequestMapping("/api/sign-in/import")
public class ImportController {

    @Autowired
    private SignInService signInService;

    @PostMapping("/data")
    public ResponseEntity<Map<String, Object>> importSignInData(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "请选择要导入的文件"
                ));
            }
            
            // 检查文件格式
            String fileName = file.getOriginalFilename();
            if (fileName == null || !(fileName.endsWith(".xlsx") || fileName.endsWith(".xls"))) {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "请上传Excel格式的文件（.xlsx或.xls）"
                ));
            }
            
            // 调用服务层进行导入
            Map<String, Object> result = signInService.importSignInData(file.getInputStream());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of(
                "success", false,
                "message", "导入失败：" + e.getMessage()
            ));
        }
    }
}